package cn.aitrox.ry.app.web.interceptor;

import cn.aitrox.ry.bean.JwtTokenCheckResult;
import cn.aitrox.ry.common.exception.CustomBizException;
import cn.aitrox.ry.common.interceptor.UserThreadLocal;
import cn.aitrox.ry.common.service.api.dto.User;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.user.feign.UserFeign;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final String X_AUTH_TOKEN = "x-auth-token";

    @Autowired
    private UserThreadLocal userThreadLocal;

    @Autowired
    @Lazy
    private UserFeign userFeign;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(X_AUTH_TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new CustomBizException(RespCodeEnum.TOKEN_MISS.getCode(), RespCodeEnum.TOKEN_MISS.getMessage());
        }
        JwtTokenCheckResult<User> tokenCheckResult = userFeign.tokenAuth(token);
        if (!tokenCheckResult.success()) {
            throw new CustomBizException(tokenCheckResult.getRespCodeEnum().getCode(), tokenCheckResult.getRespCodeEnum().getMessage());
        }
        userThreadLocal.setUser(tokenCheckResult.getCustomPayload());
        response.setHeader(X_AUTH_TOKEN, tokenCheckResult.getCustomPayload().getToken());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        userThreadLocal.clear();
    }
}
